package com.example.bes014.multiple.ds.demo.config;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.mapping.MappedStatement;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;

@Intercepts({
    @Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
    )
})
public class DataSourceLoggingInterceptor1 implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 执行查询前后，获取数据源信息
        Object result = invocation.proceed();  // 执行查询操作

        // 获取执行操作时的 DataSource
        Executor executor = (Executor) invocation.getTarget();
        Connection connection = executor.getTransaction().getConnection();
        
        if (connection != null) {
            printDataSourceInfo(connection);
        }

        return result;  // 返回查询结果
    }

    private void printDataSourceInfo(Connection connection) {
        try {
            // 获取数据库元数据
            DatabaseMetaData metaData = connection.getMetaData();
            System.out.println("=== DataSource Info ===");
            System.out.println("Database URL          : " + metaData.getURL());
            System.out.println("Database User         : " + metaData.getUserName());
            System.out.println("Database Product      : " + metaData.getDatabaseProductName());
            System.out.println("Driver Name           : " + metaData.getDriverName());
            System.out.println("Driver Version        : " + metaData.getDriverVersion());
            System.out.println("user name: " + connection.getMetaData().getUserName());
            System.out.println("=======================");
            if ("bes@192.168.92.1".equals(connection.getMetaData().getConnection().getMetaData().getUserName())) {
                StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
                for (StackTraceElement element : stackTrace) {
                    System.out.println(element);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // 可从外部配置中获取参数，这里暂不使用
    }
}
